package com.sch.wanandroid.ui.my.collect

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.sch.wanandroid.entity.ArticleBean
import com.sch.wanandroid.entity.CollectBean
import com.sch.wanandroid.network.NetWorkManager
import kotlinx.coroutines.launch

/**
 * Created by Sch.
 * Date: 2020/12/15
 * description:
 */
class MyCollectViewModel : ViewModel() {
    private val _collectList = MutableLiveData<List<CollectBean>>()
    val collectListLiveData: LiveData<List<CollectBean>> = _collectList
    private val _errorMsg = MutableLiveData<String?>()
    val errorMsg: LiveData<String?> = _errorMsg

    private val _uncollectSuccess = MutableLiveData<Boolean>()
    val uncollectSuccess: LiveData<Boolean> = _uncollectSuccess

    fun getCollectList(pageNum: Int) {
        viewModelScope.launch {
            try {
                val result = NetWorkManager.apiService.getCollectList(pageNum)
                if (result.errorCode != 0) {
                    _errorMsg.value = result.errorMsg
                } else {
                    _collectList.value = result.data.datas
                }
            } catch (e: Exception) {
                _errorMsg.value = e.toString()
            }
        }
    }

    fun unCollect(id: Int, originId: Int) {
        viewModelScope.launch {
            try {
                val result = NetWorkManager.apiService.unCollect(id, originId)
                if (result.errorCode == 0) {
                    _uncollectSuccess.value = true
                } else {
                    _errorMsg.value = result.errorMsg
                }

            } catch (e: Exception) {
                _errorMsg.value = e.toString()
            }
        }
    }
}